﻿Namespace Validation
    Public Class IntegerValidationRule
        Inherits WPFGlue.Validation.ValidationRule

        Public Property MaxValue As Nullable(Of Int64)
        Public Property MinValue As Nullable(Of Int64)

        Private _RegEx As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("^[\+-]?\d{1,19}$")
        Public Sub New()
            MyClass.New(Int64.MinValue, Int64.MinValue, "Must be integer between {1} and {2}")
        End Sub

        Public Sub New(ByVal minValue As Int64, ByVal maxValue As Int64, ByVal message As String)
            Me.ValidationStep = System.Windows.Controls.ValidationStep.RawProposedValue
            Me.Message = message
            Me.MaxValue = maxValue
            Me.MinValue = minValue
        End Sub

        Protected Overrides Function ValidateCore(ByVal value As Object, ByVal cultureInfo As System.Globalization.CultureInfo) As Boolean
            Dim result As Boolean = _RegEx.IsMatch(value)
            If result And MinValue.HasValue Then
                result = Int64.Parse(value) >= MinValue
            End If
            If result And MaxValue.HasValue Then
                result = Int64.Parse(value) <= MaxValue
            End If
            Return result
        End Function

        Protected Overrides Function FormatMessage(ByVal value As Object) As String
            Return String.Format(Me.Message, value, MinValue, MaxValue)
        End Function
    End Class
End Namespace
